<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { Secret, LabelSelector } from "@/views/domain/kubeHud/api/k8s/types";
import { useK8SApi } from "@/views/domain/kubeHud/api/k8s/k8s";
import { getAge, objectToList, timeTrans } from "@/views/domain/kubeHud/utils";
import RouterLinkBtn from "@/views/widgets/RouterLinkBtn/index.vue";

type Prop = {
  namespace?: string;
  nodeName?: string;
  selector?: LabelSelector;
  secrets?: Secret[];
};

const { secretRepo } = useK8SApi();
const props = defineProps<Prop>();
const emit = defineEmits(["update:secrets"]);

const secretList = ref<Secret[]>();
const total = ref(0);
const nextToken = ref();
const loading = ref(false);

const labelSelector = computed(() => {
  const srcs = [
    props.nodeName ? `spec.nodeName=${props.nodeName}` : "",
    props.namespace ? `metadata.namespace=${props.namespace}` : "",
    ...objectToList(props.selector).map(v => `${v.key}=${v.value}`)
  ];
  return srcs.filter(v => v !== "").join(",");
});

const loadSecretList = async () => {
  loading.value = true;
  const { items, metadata } = await secretRepo.getSecret({
    namespace: props.namespace,
    labelSelector: labelSelector.value,
    continue: nextToken.value
  });

  if (items) {
    secretList.value = items;
    nextToken.value = metadata?.continue;
    total.value = metadata.remainingItemCount ?? items?.length;
    emit("update:secrets", secretList.value);
  }
  loading.value = false;
};

onMounted(() => {
  loadSecretList();
});

watch(
  () => props.namespace,
  () => {
    loadSecretList();
  }
);
</script>

<template>
  <div v-loading="loading">
    <div />
    <el-table :data="secretList" table-layout="auto">
      <el-table-column prop="metadata.name" label="名称">
        <template #default="{ row }">
          <RouterLinkBtn
            to="/storage/secret/details"
            :query="{
              name: row.metadata.name,
              namespace: row.metadata.namespace
            }"
            :label="row.metadata.name"
          />
        </template>
      </el-table-column>

      <el-table-column prop="metadata.creationTimestamp" label="创建时间">
        <template #default="{ row }">
          {{ timeTrans(row.metadata.creationTimestamp, "YYYY-MM-DD HH:mm:ss") }}
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<style lang="scss" scoped></style>
